
require "Common/define"
require "Common/protocal"
require "Common/functions"
Event = require 'events'

require "3rd/pbc/protobuf"

Network = {};
local this = Network;

local transform;
local gameObject;
local islogging = false;
--存储消息分发的字典<protocal,function>
local handlers={};

function Network.Start() 
    logWarn("Network.Start!!");
    Event.AddListener(Protocal.Connect, this.OnConnect); 
    Event.AddListener(Protocal.Message, this.OnMessage); 
    Event.AddListener(Protocal.Exception, this.OnException); 
    Event.AddListener(Protocal.Disconnect, this.OnDisconnect); 

    --注册pbc
    Network.RegPBC();

    --绑定消息分发
    LoginHandler.New(handlers);
    GameHandler.New(handlers);
end

--注册pb文件
function Network.RegPBC()
    local path = AppConst.FrameworkRoot.."/lua/3rd/pbc/pbdata.pb";
    log('io.open--->>>'..path);
    local addr = io.open(path, "rb")
    local buffer = addr:read "*a"
    addr:close()
    protobuf.register(buffer)
end

--Socket消息--
function Network.OnSocket(key, data)
    Event.Brocast(tostring(key), data);
end

--当连接建立时--
function Network.OnConnect() 
    logWarn("Game Server connected!!");
end

--异常断线--
function Network.OnException() 
    islogging = false; 
    NetManager:SendConnect();
   	logError("OnException------->>>>");
end

--连接中断，或者被踢掉--
function Network.OnDisconnect() 
    islogging = false; 
    logError("OnDisconnect------->>>>");
end

--正常消息的接收和解析
function Network.OnMessage(buffer)
    local pbId=buffer:ReadShort();
    local message=buffer:ReadBuffer();
    log(pbId)
    handlers[pbId](message);
end

--卸载网络监听--
function Network.Unload()
    Event.RemoveListener(Protocal.Connect);
    Event.RemoveListener(Protocal.Message);
    Event.RemoveListener(Protocal.Exception);
    Event.RemoveListener(Protocal.Disconnect);
    logWarn('Unload Network...');
end

--封装bytebuffer，发送
function Network.Send(reqId,message)
    local buffer = ByteBuffer.New();
    buffer:WriteShort(reqId);
    if(message~=nil)then
        buffer:WriteBuffer(message);
    end
    networkMgr:SendMessage(buffer);
end